package xyz.xtt.user.controller;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.json.JSONUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.common.response.ApiResult;
import xyz.xtt.pay.client.response.TblPayOrderDto;
import xyz.xtt.user.api.dto.TblUserFundRecordDto;
import xyz.xtt.user.api.dto.UpdateFundSettledRequest;
import xyz.xtt.user.entity.TblUserFundRecord;
import xyz.xtt.user.service.ITblUserFundAccountService;

/**
 * @author dale
 * @date 2025/2/27
 **/
@Tag(name = "用户资金账户管理", description = "用户资金账户管理")
@Slf4j
@RequestMapping("/api/nft/user/fund")
@RestController
public class UserFundAccountController {
	@Autowired
	private ITblUserFundAccountService userFundAccountService;
	@Autowired
	private ITblUserFundAccountService iTblUserFundAccountService;

	@RequestMapping("/getNeedSettleRecords")
	public ApiResult<List<TblUserFundRecordDto>> getNeedSettleRecords(@RequestParam("maxCount") @Positive Integer maxCount,
			@RequestParam(value = "lastId", required = false) Long lastId) {
		return ApiResult.ok(convertFundRecordDtoList(userFundAccountService.getNeedSettleRecords(maxCount, lastId)));
	}

	@PostMapping("/updateFundSettled")
	public ApiResult<Boolean> updateFundSettled(@RequestBody @Valid UpdateFundSettledRequest request) {
		return ApiResult.ok(userFundAccountService.updateFundSettled(request.getUserFundRecordId()));
	}

	private List<TblUserFundRecordDto> convertFundRecordDtoList(List<TblUserFundRecord> needSettleRecords) {
		if (CollectionUtils.isEmpty(needSettleRecords)) {
			return null;
		}
		return needSettleRecords.stream().map(record -> {
			TblUserFundRecordDto dto = new TblUserFundRecordDto();
			BeanUtils.copyProperties(record, dto);
			return dto;
		}).toList();
	}

	@PostMapping("/handleOrderPaySuccess")
	public ApiResult<Boolean> handleOrderPaySuccess(@RequestBody TblPayOrderDto payOrderDto) {
		log.info("/api/nft/user/fund/handleOrderPaySuccess:{}",JSONUtil.toJsonStr(payOrderDto));
		Boolean handleOrderPaySuccess = iTblUserFundAccountService.handleOrderPaySuccess(payOrderDto);
		return ApiResult.ok(handleOrderPaySuccess);
	}
}
